<!--
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../../bower_components/iron-flex-layout/iron-flex-layout-classes.html">
<link rel="import" href="../../bower_components/neon-animation/neon-shared-element-animatable-behavior.html">
<link rel="import" href="../../bower_components/neon-animation/neon-animatable.html">
<link rel="import" href="../../bower_components/neon-animation/animations/ripple-animation.html">
<link rel="import" href="../../bower_components/neon-animation/animations/hero-animation.html">
<link rel="import" href="../../bower_components/neon-animation/animations/fade-out-animation.html">
<link rel="import" href="../../bower_components/neon-animation/animations/transform-animation.html">
<link rel="inport" href="simulation-info.html">

<link rel="import" href="../../bower_components/paper-item/paper-item.html">
<link rel="import" href="../../bower_components/paper-item/paper-item-body.html">
<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../../bower_components/paper-card/paper-card.html">


<link rel="import" href="../../bower_components/neon-animation/neon-animated-pages.html">
<link rel="import" href="../../bower_components/neon-animation/neon-animations.html">
<link rel="import" href="listFile/list-view.html">
<link rel="import" href="listFile/full-log-view.html">

<dom-module id="fullsize-page-with-card">
    <template>
        <style>

            :host {
                display: block;
                color:black;
                font-size: medium;
            }
            .fixed {
                background-color: white;
                color:black;
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                min-width: 1024px;
                min-height: 768px;
                overflow-x: visible;
            }

            .dinamic_container{
                position: relative;
                margin: 50px auto auto 25%;
                width: 780px;
                height: 580px;
                min-width: 780px;
                min-height: 580px;
                background-color:  #B8C4CC;

            }
            .card {
                width: 780px;
                height: 580px;
                min-width: 780px;
                min-height: 580px;

                @apply(--layout-horizontal);
            }

            .simulation-container{
                width: 350px;
                height: 560px;
                @apply(--layout-vertical);
            }


            #back_button{
                float: left;

            }

            paper-card {
                --paper-card-header-color:black;
                background-color: transparent;

            }

            div.animation-log-container{
                width:100%;
                min-width: 300px;
                margin-left: 30px;


            }
            neon-animated-pages {
                height: 550px;
            }
            paper-button[raised]{
                width: 150px;
                border-radius: 50px;
            }

            .download-button-container{
                color:black;
                cursor: pointer;
                @apply(--layout-horizontal);
                @apply(--layout-center);
            }

             #sim_viewer{
                 overflow: scroll;
             }
              #viewer_grid{
                  border:0;
              }






        </style>
     <div class="layout vertical center-justified">
        <div id="fixed" class="fixed horizontal layout">
            <div on-click="go_back">
                <paper-button><iron-icon icon="arrow-back"></iron-icon> BACK</paper-button>
            </div>
            <div class="flex"></div>
            <div on-click="go_next">
                <paper-button> NEXT<iron-icon icon="arrow-forward"></iron-icon></paper-button>
            </div>

        </div>

         <neon-animated-pages id="system_info" class="dinamic_container" selected="0" on-iron-select="startViewer" on-iron-deselect="stopViewer">
                 <div id="card" class="card">
                     <div class="simulation-container">
                         <paper-card id="sim_info" heading="Simulation Info">
                             <div class="card-content">
                                 <simulation-info id="sim_info_resume" sim="{{sim}}" ></simulation-info>
                             </div>
                         </paper-card>
                         <div class="flex">
                             <div id="SystemCPUMonitor" style="height: 200px; min-width: 300px;"></div>
                         </div>
                         <div class="download-button-container" on-click="downloadLog">
                             <form id="download_log_form" method="POST" action="/downloadLogs?id={{sim.id}}">
                                 <paper-icon-button icon="file-download" raised></paper-icon-button>
                                 <span>Download Logs</span>
                             </form>
                         </div>
                     </div>
                     <div class="flex">

                     </div>
                     <div class="animation-log-container">
                         <neon-animated-pages id="log_files" selected="0">
                             <list-view list_log="{{listFile}}" on-item-click="_onItemClick"></list-view>
                             <full-log-view id="full_file" on-close="_onClose"></full-log-view>
                         </neon-animated-pages>
                     </div>
                </div>


                <div id="sim_viewer" class="card" >
                    <table id="viewer_grid" cellspacing="0"></table>
                </div>

         </neon-animated-pages>




     </div>
    </template>

</dom-module>

<script>
    Polymer({
        is: 'fullsize-page-with-card',
        behaviors: [
            Polymer.NeonSharedElementAnimatableBehavior
        ],
        properties: {
            sim:{
                type: Object
            },
            listFile:{
                type:Array
            },
            sharedElements: {
                type: Object,
                value: function() {
                    return {
                        'hero': this.$.card,
                        'ripple': this.$.fixed
                    }
                }
            },

            viewer:{
                type: Boolean
            },

            animationConfig: {
                type: Object,
                value: function() {
                    return {
                        'entry': [{
                            name: 'ripple-animation',
                            id: 'ripple',
                            toPage: this,
                        }, {
                            name: 'hero-animation',
                            id: 'hero',
                            toPage: this,
                            timing: {
                                delay: 150
                            }
                        }],
                        'exit': [{
                            name: 'fade-out-animation',
                            node: this.$.fixed
                        }, {
                            name: 'transform-animation',
                            transformFrom: 'none',
                            transformTo: 'translate(0px,-200vh) scale(0.9,1)',
                            node: this.$.system_info
                        }]
                    }
                }
            }
        },
        observers:[
                'AVGCPUWorkLoad(sim)'
        ],

        go_back:function(){
            var scope = document.querySelector('neon-animated-pages [id="system_info"]');
            if(scope.selected==0)
                this.fire('go-back');

            else{
                scope.entryAnimation = 'slide-from-left-animation';
                scope.exitAnimation = 'slide-right-animation';
                //scope.selected =0;
                scope.selectPrevious();
            }
        },
        go_next: function(){
            var scope = document.querySelector('neon-animated-pages [id="system_info"]');
            if(scope.selected!=1){
                scope.entryAnimation = 'slide-from-right-animation';
                scope.exitAnimation = 'slide-left-animation';
                scope.selectNext();
            }
        },
        _onItemClick: function(event) {
            var item = event.detail.data;
            if(item)
                this.$.full_file.content = item.content;
            this.$.log_files.selected = 1;
        },
        _onClose: function(event) {
            this.$.log_files.selected = 0;
        },

        downloadLog: function(event){
            //history.pushState(null,null,"/downloadLogs?id="+this.sim.id);
            this.$.download_log_form.submit();
        },

        startViewer: function(){

            if(this.$.system_info.selected == 1) {
                   console.log(this.sim);
                var that = this;
                $.ajax({
                    url: "viewer",
                    data: "id=" + this.sim.id + "&cmd=startViewer",
                    success: function (result) {
                        console.log("ho fatto partire il viewer")
                        that.viewer = true;
                         viewerTimeOut = setInterval(function(){that.take_snapshot(that.viewer)}, 1000);
                    }
                });
            }
        },
        stopViewer: function(){

            if(this.$.system_info.selected == 0) {
                var that = this;
                $.ajax({
                    url: "viewer",
                    data: "id=" + this.sim.id + "&cmd=stopViewer",
                    success: function (result) {
                        that.viewer = false;
                        clearInterval(viewerTimeOut);
                    }
                });
            }
        },
        take_snapshot: function (viewer){
            if(viewer){
                var that = this;
                $.ajax({
                    url:"requestImage",
                    data:"id="+this.sim.id+"&step="+this.sim.step,
                    success: function(result){
                          that._updateviewerGrid(result);
                    }});
            }
        },

        _updateviewerGrid: function(result){
            var rows = this.sim.rows;
            var cols = this.sim.columns;
            var r,c;
            var grid = $("#viewer_grid");
            $(grid).empty();
            var snapshot = JSON.parse(result);

            var imgs = snapshot["snapshot"]["step"];

            for(r=0; r<rows; r++){
                var tr = $("<tr></tr>");
                for(c=0; c<cols; c++){
                    var celltype = r+"-"+c;
                    var base64 =  imgs[celltype];
                    console.log(base64);
                      tr.append("<td><img src=\"data:image/png;base64,"+base64+"\"></td>");
                }
                grid.append(tr);
            }
        },
        AVGCPUWorkLoad: function (sim) {



            Highcharts.setOptions({
                global : {
                    useUTC : false
                }
            });

            // Create the chart
            $('#SystemCPUMonitor').highcharts({
                        colors: ["#2b908f", "#90ee7e", "#f45b5b", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee",
                            "#55BF3B", "#DF5353", "#7798BF", "#aaeeee"],
                        chart: {
                            type: 'gauge',
                            backgroundColor: 'transparent',
                            style: {
                                fontFamily: "'Unica One', sans-serif",
                            },
                            plotBorderColor: '#606063',
                            marginTop:'25'

                        },
                        exporting: 'false',
                        title: {
                            text: 'AVG CPU Load',
                            style: {
                                color: '#000000',
                                textTransform: 'uppercase',
                                fontSize: '20px'
                            }
                        },
                        subtitle: {
                            style: {
                                color: '#E0E0E3',
                                textTransform: 'uppercase'
                            }
                        },
                        credits: false,
                        pane: {
                            startAngle: -150,
                            endAngle: 150,
                            background: [{
                                backgroundColor: {
                                    linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                                    stops: [
                                        [0, '#FFF'],
                                        [1, '#333']
                                    ]
                                },
                                borderWidth: 0,
                                outerRadius: '109%'
                            }, {
                                backgroundColor: {
                                    linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
                                    stops: [
                                        [0, '#333'],
                                        [1, '#FFF']
                                    ]
                                },
                                borderWidth: 1,
                                outerRadius: '107%'
                            }, {
                                // default background
                            }, {
                                backgroundColor: '#DDD',
                                borderWidth: 0,
                                outerRadius: '105%',
                                innerRadius: '103%'
                            }]
                        },

                        // the value axis
                        yAxis: {
                            min: 0,
                            max: 100,

                            minorTickInterval: 'auto',
                            minorTickWidth: 1,
                            minorTickLength: 10,
                            minorTickPosition: 'inside',
                            minorTickColor: '#0000ff',

                            tickPixelInterval: 30,
                            tickWidth: 2,
                            tickPosition: 'inside',
                            tickLength: 10,
                            tickColor: '#0000ff',
                            labels: {
                                step: 2,
                                rotation: 'auto'
                            },

                            title: {
                                text: '%'
                            },
                            plotBands: [{
                                from: 0,
                                to: 50,
                                color: '#00ff66' // green
                            }, {
                                from: 50,
                                to: 80,
                                color: '#ffff00' // yellow
                            }, {
                                from: 80,
                                to: 100,
                                color: '#ff0000' // red
                            }]
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0, 0, 0, 0.85)',
                            style: {
                                color: '#F0F0F0'
                            }
                        },
                        series: [{
                            name: 'CPU Load',
                            data: [0],
                            tooltip: {
                                valueSuffix: ' %'
                            }
                        }]

                    },
                    // Add some life
                    function (chart) {
                        if (!chart.renderer.forExport) {
                           /* refreshIntervalId=  setInterval(function () {*/

                                    var point = chart.series[0].points[0],
                                            newVal;

                                    $.ajax({
                                        url: "getWorkersInfoBySimID",
                                        data: "id=" + sim.id,
                                        success: function (result) {

                                            var obj = [];
                                            if (result.length > 0)
                                                obj = JSON.parse(result);
                                            if (obj.hasOwnProperty('workers')) {

                                                var cpu_avg = 0;
                                                for (var w, i = 0; w = obj.workers[i]; i++) {

                                                    cpu_avg += w.cpuLoad;
                                                }
                                                newVal = Math.floor(cpu_avg / obj.workers.length);

                                            } else {
                                                newVal = point.y;
                                            }
                                            point.update(newVal);
                                        }
                                    });
                           /* }, 1000);*/
                        }
            });

        }

    });


</script>